package com.zhkj.txg.module.mine.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.text.format.Formatter
import android.view.View
import androidx.core.text.buildSpannedString
import androidx.core.text.scale
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.R
import com.zhkj.txg.module.home.ui.MainActivity
import com.zhkj.txg.module.home.ui.WelfareActivity
import com.zhkj.txg.module.mine.vm.SettingViewModel
import com.zhkj.txg.utils.FileUtils
import com.zhkj.txg.utils.ProgressDrawable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.subscribeBy
import kotlinx.android.synthetic.main.activity_setting.*
import zlc.season.rxdownload4.download

class SettingActivity : ViewModelActivity<SettingViewModel>() {
    override fun setViewModel(): SettingViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleSetting
    override val layoutResId: Int = R.layout.activity_setting

    override fun initUI() {
        // 消息中心
        tvSystemMessage.setOnClickListener {
            val intent = Intent(this, SystemNotificationActivity::class.java)
            startActivity(intent)
        }
        // 账户与安全
        tvSystemSafe.setOnClickListener {
            startActivity(Intent(this, AccountSafeActivity::class.java))
        }
        // 帮助
        tvSystemHelp.setOnClickListener {
            startActivity(Intent(this, GuideListActivity::class.java))
        }
        // 缓存
        viewSystemCache.setOnClickListener {
            if (FileUtils.deleteFile(cacheDir)) {
                val size = FileUtils.getFolderSize(cacheDir)
                toast("清除缓存成功")
                tvSystemCache.text = Formatter.formatFileSize(this, size)
            } else toast("清除缓存失败")
        }
        // 用户协议
        tvSystemProtocol.setOnClickListener {
            WelfareActivity.agreement(this, tvSystemProtocol.text.toString())
        }
        viewSystemVersion.setOnClickListener {
            viewModel.getVersion()
//            val progressDrawable = ProgressDrawable()
//            btnDownload.background = progressDrawable
//            // 检查更新
//            val url = "https://dldir1.qq.com/weixin/android/weixin706android1460.apk"
//
//            val rxPermission = RxPermissions(this)
//            rxPermission.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                .subscribe {
//                    if (!it) {
//                        return@subscribe
//                    }
//                    url.download()
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribeBy(
//                            onNext = {
//                                btnDownload.text = "${it.downloadSizeStr()}/${it.totalSizeStr()}"
//                            },
//                            onComplete = {
////                        state = COMPLETED
//                                btnDownload.text = "安装"
//                            },
//                            onError = {
////                        state = FAILED
//                                LogUtils.e(it.message)
//                                btnDownload.text = "重试"
//                            }
//                        )
//                }
        }
        // 关于
        tvSystemAbout.setOnClickListener {
            WelfareActivity.aboutUs(this, tvSystemAbout.text.toString())
        }
        tvSystemLogout.setOnClickListener {
            viewModel.logout(AccountManager.getToken())
        }
        // 隐私政策
        tvSystemPolicy.setOnClickListener {
            WelfareActivity.policy(this, tvSystemPolicy.text.toString())
        }
    }

    override fun initData() {
        // 获取Glide缓存目录，以及缓存目录大小
        val size = FileUtils.getFolderSize(cacheDir)
        tvSystemCache.text = Formatter.formatFileSize(this, size)
        // 获取版本号
        val packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_META_DATA)
        tvSystemVersion.text =
            buildSpannedString { scale(0.7f) { append("v") }.append(packageInfo.versionName) }
    }

    override fun initViewModel() {
        viewModel.logoutLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                val intent = Intent(this, MainActivity::class.java)
                    .putExtra(MainActivity.LOGOUT, true)
                intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
                startActivity(intent)
            }
        })


        viewModel.versionLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                val json = Gson()
                LogUtils.e(json.toJson(it.response?.data))
                it.response?.data?.let { entity ->
                    val packageInfo =
                        packageManager.getPackageInfo(packageName, PackageManager.GET_META_DATA)
                    if (entity.versionCode == packageInfo.versionCode) {
                        toast("最新版本")
                    } else {
                        toast("发现新版本")
                    }
                }
            }
        })
    }
}